package org.example.log.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.InputStreamReader;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 构建缓存
 *
 * @author hero生仔
 * @date 2025/8/2
 */
@Component
public class ModelFieldCache implements CommandLineRunner {
    /**
     * 树名 -> 模型数据
     */
    private final Map<String, JSONObject> MODEL_FIELD_CACHE = new ConcurrentHashMap<>();

    /**
     * 文件名 -> 文件数据
     */
    Map<String, JSONObject> FILE_CACHE = new ConcurrentHashMap<>();

    @Autowired
    private ResourcePatternResolver resourcePatternResolver;

    /**
     * 通过树名来获取模型缓存字段
     *
     * @param treeName 决策树
     * @return 模型字段
     */
    public JSONObject getModelFieldByTreeName(String treeName) {
        return MODEL_FIELD_CACHE.getOrDefault(treeName, new JSONObject());
    }

    /**
     * 获取表名
     *
     * @param modelName 模型名
     * @return 表名
     */
    public String getTableName(String modelName) {
        return Optional.ofNullable(FILE_CACHE.get(modelName)).orElse(new JSONObject()).getJSONObject("DEFAULT").getString("tableName");
    }

    /**
     * 构建模型数据缓存
     */
    public void createModelDatas() {
        for (Map.Entry<String, JSONObject> entry : FILE_CACHE.entrySet()) {
            // 模型名
            String modelName = entry.getKey();
            // 模型属性
            JSONObject modelJsonObj = entry.getValue().getJSONObject("DEFAULT");
            JSONObject fieldsMapping = modelJsonObj.getJSONObject("fieldsMapping");

            // 决策树和模型映射起来
            JSONArray treeList = modelJsonObj.getJSONArray("treeList");
            JSONObject diffFieldObject = Optional.ofNullable(modelJsonObj.getJSONObject("treeDiff")).orElse(new JSONObject());
            for (Object treeObj : treeList) {
                String tree = (String) treeObj;
                // 模型名为key的map
                Map<String, Object> modelMiddleMap = new JSONObject();
                JSONObject fieldsMappingClone = (JSONObject) fieldsMapping.clone();
                // 差异化覆盖默认的映射值
                fieldsMappingClone.putAll(Optional.ofNullable(diffFieldObject.getJSONObject(tree)).orElse(new JSONObject()));
                // 模型名 -> 模型的默认的中间层字段
                modelMiddleMap.put(modelName, fieldsMappingClone);
                if (MODEL_FIELD_CACHE.containsKey(tree)) {
                    JSONObject oldJsonObject = MODEL_FIELD_CACHE.get(tree);
                    oldJsonObject.putAll(modelMiddleMap);
                } else {
                    MODEL_FIELD_CACHE.put(tree, (JSONObject) modelMiddleMap);
                }
            }
        }
    }

    @Override
    public void run(String... args) throws Exception {
        Resource[] resources = resourcePatternResolver.getResources("classpath:config" + "/*");
        for (Resource resource : resources) {
            if (resource.isReadable() && !Objects.requireNonNull(resource.getFilename()).contains("/")) { // 跳过子目录
                try (InputStreamReader reader = new InputStreamReader(resource.getInputStream())) {
                    StringBuilder content = new StringBuilder();
                    char[] buffer = new char[1024];
                    int bytesRead;
                    while ((bytesRead = reader.read(buffer)) != -1) {
                        content.append(buffer, 0, bytesRead);
                    }
                    int index = resource.getFilename().lastIndexOf(".");
                    FILE_CACHE.put(resource.getFilename().substring(0, index), JSON.parseObject(content.toString()));
                }
            }
        }

        // 构建模型数据缓存
        createModelDatas();
    }
}
